//
//  GeexAVSeparation.m
//  GeexCustomer
//
//  Created by zhangbaochuan on 2020/8/31.
//  Copyright © 2020 Geex. All rights reserved.
//

//#import <lame/lame.h>
#import "GZZAudioConverter.h"

#import "GeexAVSeparation.h"

@implementation GeexAVSeparation

+ (instancetype)sharedInstance {
    static GeexAVSeparation *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[GeexAVSeparation alloc] init];
    });
    return instance;
    
}

//视频路径
+ (NSString *)getPathMP3{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYYMMdd"];
    NSString *dateStr = [formatter stringFromDate:[NSDate date]];
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3", dateStr]];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSError *error;
        if ([[NSFileManager defaultManager] removeItemAtPath:path error:&error] == NO) {
            
        }
    }
    return path;
}

//视频路径
+ (NSString *)getPathCaf{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYYMMdd"];
    NSString *dateStr = [formatter stringFromDate:[NSDate date]];
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.caf", dateStr]];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSError *error;
        if ([[NSFileManager defaultManager] removeItemAtPath:path error:&error] == NO) {
            
        }
    }
    return path;
}

+ (NSString *)getPathm4a{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYYMMdd"];
    NSString *dateStr = [formatter stringFromDate:[NSDate date]];
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.m4a", dateStr]];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSError *error;
        if ([[NSFileManager defaultManager] removeItemAtPath:path error:&error] == NO) {
            
        }
    }
    return path;
}
//视频路径
+ (NSString *)getPath{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYYMMdd"];
    NSString *dateStr = [formatter stringFromDate:[NSDate date]];
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4", dateStr]];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSError *error;
        if ([[NSFileManager defaultManager] removeItemAtPath:path error:&error] == NO) {
            
        }
    }
    return path;
}

+(void)accessAudioFromVideo:(NSURL *)videoPath completion:(void (^)(NSURL *outputPath,BOOL isSucceed)) completionHandle{
   
     AVAsset *videoAsset = [AVAsset assetWithURL:videoPath];
    //1创建一个AVMutableComposition
    AVMutableComposition *mixComposition = [[AVMutableComposition alloc]init];
    //2 创建一个轨道,类型为AVMediaTypeAudio
    AVMutableCompositionTrack *audioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    
    //获取videoPath的音频插入轨道
    [audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:kCMTimeZero error:nil];
    
    //4创建输出路径
    NSString *path = [self getPathm4a];
    
    NSURL *outputURL = [NSURL fileURLWithPath:path];
    
    //5创建输出对象
    AVAssetExportSession *exporter = [[AVAssetExportSession alloc]initWithAsset:mixComposition presetName:AVAssetExportPresetAppleM4A];
    exporter.outputURL = outputURL ;
    exporter.outputFileType = AVFileTypeAppleM4A;
    exporter.shouldOptimizeForNetworkUse = YES;
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        if (exporter.status == AVAssetExportSessionStatusCompleted) {
            NSURL *outputURL = exporter.outputURL;
            completionHandle(outputURL,YES);
            
            [self configM4a:path withMp3:[self getPathMP3]];
        }else {
            NSLog(@"失败%@",exporter.error.description);
            completionHandle(outputURL,NO);
        }
    }];
    
}

+ (void)configM4a:(NSString *)m4pPath withMp3:(NSString *)mp3Path{
    dispatch_async(dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL), ^ {
        GZZAudioConverter *converter = [[GZZAudioConverter alloc] init];
        converter.inputFile = m4pPath;
        converter.outputFile = mp3Path;
        converter.outputFileType = kAudioFileMP3Type;
        converter.outputFormatID = kAudioFormatMPEGLayer3;
        BOOL success = [converter convert];
        dispatch_async(dispatch_get_main_queue(), ^ {
            if (success) {
                NSLog(@"转换成功");
            } else {
                NSLog(@"转换失败");
            }
        });
    });
}

//  输出路径
+ (NSURL *)exporterPath:(NSString *)filename{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"selfMusic%@.%@",str,filename];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docPath = [paths firstObject];
    //这个是录制视频时存储到本地的video
    NSString *path = [NSString stringWithFormat:@"%@/KSYShortVideoCache",docPath];
    //判断文件夹是否存在，不存在就创建
    //创建附件存储目录
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *outputFilePath = [path stringByAppendingPathComponent:fileName];
    return [NSURL fileURLWithPath:outputFilePath];
}




@end
